﻿using Sidvall.AuthorizationManager.Net.Services.V1;
using Sidvall.Collections;
using System.Threading.Tasks;

namespace Sidvall.AuthorizationManager
{
	public class ServerManager
	{
		#region Public Members

		protected System.Collections.Generic.Dictionary<long, AuthorizationScope> AuthorizationScopeIndex { get; private set; }

		#region InitializeAsync

		public async Task InitializeAsync(int? serverConnectionId)
		{
			System.Collections.Generic.List<System.Threading.Tasks.Task> tasks;

			tasks = new System.Collections.Generic.List<System.Threading.Tasks.Task>();
			tasks.Add(LoadAuthorizationScopeIndexAsync(serverConnectionId));
			await System.Threading.Tasks.Task.WhenAll(tasks).ConfigureAwait(false);
		}

		#endregion

		#endregion
		#region Private Members

		#region LoadAuthorizationScopeIndexAsync

		private async Task LoadAuthorizationScopeIndexAsync(int? serverConnectionId)
		{
			var criteria = new Sidvall.Data.FetchListCriteria<Data.Fields.AuthorizationScopeField, Data.Relations.AuthorizationScopeRelation>();
			ParameterManager.InitializeParameters(criteria, serverConnectionId);
			var items = await Sidvall.AuthorizationManager.SystemContext.Current.DataPortal.AuthorizationScopeManager.GetItemsAsync(criteria).ConfigureAwait(false);
			this.AuthorizationScopeIndex = items.Items.ToDictionary(o => o.AuthorizationScopeId.Value, true);
		}

		#endregion

		#endregion
		#region Constructors

		public ServerManager()
		{
		}

		#endregion
	}
}
